package com.xbhog.screwdemo.demos;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class EllipseCenterExample {
    public static void main(String[] args) {
        int width = 400;
        int height = 400;
        int ellipseX = 50; // 椭圆左上角的 x 坐标
        int ellipseY = 50; // 椭圆左上角的 y 坐标
        int ellipseWidth = 300; // 椭圆的宽度
        int ellipseHeight = 200; // 椭圆的高度

        // 创建一个空白的 BufferedImage
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();

        try {
            // 绘制椭圆
            g2d.setColor(Color.WHITE); // 设置颜色
            g2d.fillOval(ellipseX, ellipseY, ellipseWidth, ellipseHeight); // 绘制椭圆

            // 计算椭圆的中心点
            double centerX = ellipseX + ellipseWidth / 2.0;
            double centerY = ellipseY + ellipseHeight / 2.0;

            // 绘制中心点的小圆圈（标记中心）
            /*g2d.setColor(Color.RED);
            g2d.fillOval((int)centerX - 5, (int)centerY - 5, 10, 10);*/

            String text = "hello world";
            // 添加文本
            g2d.setColor(Color.BLACK); // 设置文本颜色
            Font font = new Font("Arial", Font.BOLD, 48);
            g2d.setFont(font);
            FontMetrics metrics = g2d.getFontMetrics();
            int textWidth = metrics.stringWidth(text);
            g2d.drawString(text, (int) centerX-textWidth/2, (int) centerY);
            // 打印椭圆的中心点坐标
            System.out.printf("Ellipse center point: (%f, %f)\n", centerX, centerY);

            // 保存图像到文件
            ImageIO.write(image, "png", new File("ellipse_center_example.png"));

            System.out.println("Image with ellipse and center point created successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            g2d.dispose();
        }
    }
}